package com.gmd.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.MappingDispatchAction;

import com.gmd.actionform.LoginForm;
import com.gmd.model.Usuario;
import com.gmd.service.ComunService;
public class PrincipalAction extends MappingDispatchAction{
	
	HttpSession lasesion;
	ComunService ser= new ComunService();
	private String usu;
	 public String getUsu() {
		return usu;
	}

	public void setUsu(String usu) {
		this.usu = usu;
	}

	public String getPas() {
		return pas;
	}

	public void setPas(String pas) {
		this.pas = pas;
	}

	private String pas;
	
	public ActionForward principal(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		lasesion = request.getSession(true);
		lasesion.invalidate();
		return mapping.findForward("exito");
	}
	
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		lasesion = request.getSession(true);
		String vista = "";
		ActionMessages errores = new ActionMessages();
		LoginForm login=(LoginForm) form;
		
				String usu = login.getUsu();
				String pas = login.getPas();
				Usuario usuario = null;
				
				usuario = ser.validarUsuarioExiste(usu);
				if (usuario != null) {
					Usuario u = new Usuario();
					u.setUsuario(usu);
					u.setClave(pas);
					Usuario usuario2 = null;
					usuario2 = ser.validarUsuarioPass(u);
					if (usuario2 != null) {
						lasesion.setAttribute("usuario", usuario);
						vista="exito";
					} else {
						errores.add("pas", new ActionMessage("error.clave.in"));
						saveErrors(lasesion, errores);
						vista = "error";
					}
				} else {
					errores.add("usu", new ActionMessage("error.usuario.ne"));
					saveErrors(lasesion, errores);
					vista = "error";
				}
		
		return mapping.findForward(vista);
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		lasesion = request.getSession(true);
		lasesion.invalidate();
		return mapping.findForward("exito");
	}


}
